#!/usr/bin/env python3
"""
每 3 秒读取 csv 第二行并作为属性上报
"""
import csv
import json
import ssl
import time
import threading
import paho.mqtt.client as mqtt

# -------------------- 配置 --------------------
HOST      = "2766b7c2d2.st1.iotda-device.cn-south-1.myhuaweicloud.com"
PORT      = 8883
CLIENT_ID = "6886edbba72147363d93bdb4_4Hxiaoche1_0_0_2025081303"
USERNAME  = "6886edbba72147363d93bdb4_4Hxiaoche1"
PASSWORD  = "9972cddd2cfd4e2d3356a1895f6ba439db5feac7e2394d188586ec03a9f3a719"
DEVICE_ID = USERNAME
CSV_FILE  = "data.csv"          # csv 文件名
# --------------------------------------------

class DeviceClient:
    def __init__(self):
        # 1. 去掉 VERSION1，使用默认最新回调 API
        self.client = mqtt.Client(
            client_id=CLIENT_ID,
            protocol=mqtt.MQTTv311
        )
        self.client.username_pw_set(USERNAME, PASSWORD)
        self.client.tls_set(cert_reqs=ssl.CERT_NONE)
        self.client.tls_insecure_set(True)
        self.client.on_connect = self._on_connect

    # ---------- 连接回调 ----------
    def _on_connect(self, cli, userdata, flags, rc):
        if rc == 0:
            print("🔗 已连接，开始 3 秒定时上报")
            self._report_csv_row()  # 首次立即上报
        else:
            print("❌ 连接失败 rc =", rc)

    # ---------- 读取 csv 第 2 行并上报 ----------
    # ---------- 读取 csv 第 2 行并上报 ----------
    def _report_csv_row(self):
        try:
            with open(CSV_FILE, newline='', encoding='UTF-8') as f:
                reader = csv.DictReader(f)
                rows = list(reader)
                if not rows:                 # 文件只有表头或为空
                    print("⚠️  无数据行，跳过本次上报")
                else:
                    last_row = rows[-1]      # 取最后一行
                    topic = "5hweb"
                    props = {"编号": 1}
                    # ② 再把 CSV 里的字段依次更新进来（不会覆盖已存在的 key）
                    props.update(last_row)

                    payload = {
                        "services": [{
                            "service_id": "4H小车_1",
                            "properties": props
                        }]
                    }
                    msg = json.dumps(payload, ensure_ascii=False)
                    print("上报内容：", msg)
                    self.client.publish(topic, msg, qos=1)
                    print(f"{time.strftime('%H:%M:%S')} csv-最新一行已上报")
        except Exception as e:
            print("读取/上报异常:", e)

        threading.Timer(3.0, self._report_csv_row).start()

    # ---------- 启动 ----------
    def start(self):
        self.client.connect(HOST, PORT, keepalive=60)
        self.client.loop_forever()

def main():
    device = DeviceClient()
    try:
        device.start()
    except KeyboardInterrupt:
        print("\n退出...")

if __name__ == "__main__":
    main()